import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

import os
import importlib

from flask import Blueprint


from settings import init as _init


class VersionBlueprint(Blueprint):
    """api url版本前缀蓝图"""

    def __init__(self, version, name, __name__, url_prefix, *args, **kwargs):
        super().__init__(name, __name__, url_prefix = '/{}{}'.format(version, url_prefix), *args, **kwargs)


def create_version_blueprint(version, name, __name__, url_prefix = '', *args, **kwargs):
    return VersionBlueprint(version, name, __name__, url_prefix, *args, **kwargs)


def create_bp_route(*, bp, prefix):
    def route(route_url, *args, **kwargs):
        return bp.route(prefix + route_url, *args, **kwargs)

    return route


def import_submodule(*, __name__, __file__):
    """作用是让路由装饰器绑定上函数   name:__name__ file:__file__"""

    for e in os.listdir(os.path.dirname(__file__)):
        if e.startswith('_'):
            continue
        importlib.import_module('{}.{}'.format(__name__, e.split('.')[0]))


def register_api_blueprints(app, package_path = 'blueprints/api_blueprints'):
    # 注册api蓝图
    if not os.path.exists(package_path):
        print('不存在api蓝图目录')
        return
    for version_dir in os.listdir(package_path):
        if version_dir.startswith('_'):
            continue
        common = importlib.import_module(
            '{}.{}._bps'.format(package_path.replace('/', '.'), version_dir)
        )

        for md_filename in os.listdir(package_path + '/' + version_dir):
            if md_filename.startswith('_'):
                continue
            # print('{}.{}.{}'.format(package_path.replace('/', '.'), version_dir, os.path.splitext(md_filename)[0]))

            mdl = importlib.import_module(
                '{}.{}.{}'.format(package_path.replace('/', '.'), version_dir, os.path.splitext(md_filename)[0]))
            # bp = getattr(mdl, 'bp_' + mdl.__name__.split('.')[-1])
            bp_name = 'bp_' + mdl.__name__.split('.')[-1]
            if not hasattr(common, bp_name):
                logger.warning('{}.{} 未定义'.format(mdl, bp_name))
                continue
            bp = getattr(common, bp_name)
            if isinstance(bp, Blueprint):
                app.register_blueprint(bp)


def register_site_blueprints(app, package_path = 'blueprints/site_blueprints'):
    # 注册网站蓝图
    if not os.path.exists(package_path):
        print('不存在site蓝图目录')
        return
    for md_filename in os.listdir(package_path):
        if not md_filename.startswith('_'):
            importlib.import_module('{}.{}'.format(package_path.replace('/', '.'), os.path.splitext(md_filename)[0]))

    common = importlib.import_module('{}._bps'.format(package_path.replace('/', '.')))
    for e in dir(common):
        if not e.startswith('bp_'):
            continue
        bp = getattr(common, e)
        if isinstance(bp, Blueprint):
            app.register_blueprint(bp)

def register_websockets(app,package_path = 'blueprints/websocket_blueprints' ):
    from flask_sockets import Sockets
    from . import wsyffw_flask_websockets
    if not os.path.exists(package_path):
        print('不存在websocket蓝图目录')
        return
    for md_filename in os.listdir(package_path):
        if not md_filename.startswith('_'):
            importlib.import_module('{}.{}'.format(package_path.replace('/', '.'), os.path.splitext(md_filename)[0]))

    sockets = wsyffw_flask_websockets.sockets = Sockets(app)
    # print(wsyffw_flask_websockets.route_storage)
    for i,e in enumerate(wsyffw_flask_websockets.route_storage):
        path, handler = e
        sockets.route(path)(handler)

def create_json_rpc(version,module_name,root ='rpc'):
    from flask_jsonrpc import JSONRPC
    from flask_jsonrpc.site import JSONRPCSite
    return  JSONRPC(
        service_url ='/{}/v{}/{}'.format(root,version,module_name),
        site = JSONRPCSite(),
        enable_web_browsable_api = True
    )

def register_rpc(app,package_path = 'blueprints/rpc_blueprints'):
    from flask_jsonrpc import JSONRPC
    if not os.path.exists(package_path):
        print('不存在websocket蓝图目录')
        return
    common = importlib.import_module('{}._jsonrpcs'.format(package_path.replace('/', '.')))
    for e in dir(common):
        if not e.startswith('jsonrpc_'):
            continue
        json_rpc = getattr(common, e)
        if isinstance(json_rpc, JSONRPC):
            json_rpc.init_app(app)

    for md_filename in os.listdir(package_path):
        if not md_filename.startswith('_'):
            importlib.import_module('{}.{}'.format(package_path.replace('/', '.'), os.path.splitext(md_filename)[0]))


def register_global_template_functions(app):
    from flask_custom import global_template_functions
    for e in dir(global_template_functions):
        if not e.startswith('gt_'):
            continue
        if len(e) == 3:
            continue
        func = getattr(global_template_functions,e)
        app.add_template_global(func, e[3:])

def get_dir_name(dir_path):
    return os.path.basename(os.path.dirname(os.path.realpath(dir_path)))


def init_all_settings(app):
    _init.init_config(app)

    def get_config(name):
        return app.config[name]

    if get_config('CORS_SWITCH'):
        _init.init_cors(app)
    if get_config('TEMPLATE_HOT_UPDATE'):
        app.jinja_env.auto_reload = True
        app.config['TEMPLATES_AUTO_RELOAD'] = True


    register_global_template_functions(app)
    register_rpc(app)
    register_websockets(app)
    register_api_blueprints(app)
    register_site_blueprints(app)
